package cn.com.xy.sms.util;

import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.ParseItemManager;
import cn.com.xy.sms.sdk.db.entity.PhoneSmsParseManager;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.util.DuoquUtils;
import cn.com.xy.sms.sdk.util.InitUtil;
import cn.com.xy.sms.sdk.util.JsonUtil;

/*SDK-490 hewengao 20160616 start */
import java.util.Map;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.action.AbsSdkDoAction;
/*SDK-490 hewengao 20160616 end */

public class BeforeParseUtil extends Thread{

    private static  final Object lock = new Object();
    private  static boolean stopParse =false;
    private  static boolean parseIng =false;
    private boolean allTable =false;
    private String phoneNum;
    private int maxLimit;
    private int parseType;
    /* SDK-556 huangzhiqiang 20160722 start */
//    private int parseAllCnt =0;
    // 记录当次批量识别的短信数量，用于日志输出
    private int parseCount = 0;
    /* SDK-556 huangzhiqiang 20160722 end */
    private boolean mResultAddMemory =false;
    private static long threadId = 0;
    /*SDK-490 hewengao 20160616 start */
    private static Map mExtend=null;
    private static int mLoadExtendCount = 0;
    /*SDK-490 hewengao 20160616 end */

    /* SDK-699 huagnzhiqiang 20161208 begin */
    private static Map<String, Object> mLogExtend = new HashMap<String, Object>();
    /* SDK-699 huagnzhiqiang 20161208 end */

    public static void setStop(){
        synchronized (lock) {
            stopParse = true;
        }
    }
    public static void executeBeforeParse(boolean allTable,String phoneNum,int maxLimit,int parseType,boolean resultAddMemory){
        
        BeforeParseUtil   beforeParseThread = new BeforeParseUtil(allTable,phoneNum,maxLimit,parseType,resultAddMemory);
        /* SDK-419 huangzhiqiang 20160504 start */
        beforeParseThread.setPriority(Thread.MIN_PRIORITY);
        /* SDK-419 huangzhiqiang 20160504 end */
        beforeParseThread.start();
    }
 
   private BeforeParseUtil(){}
   private BeforeParseUtil(boolean allTable,String phoneNum,int maxLimit,int parseType,boolean resultAddMemory){
       this.allTable = allTable;
       this.phoneNum = phoneNum;
       this.maxLimit = maxLimit;
       this.parseType = parseType;
       this.mResultAddMemory = resultAddMemory;
       this.setName("before_parse_thread");
//       LogManager.d("duoqu_xiaoyuan", "BeforeParseUtil phoneNum: "+phoneNum+"    parseType: "+parseType);
   }
    private boolean getRunPower(){
        int checkCnt = 0;
        do{
            //调用sdk是否已初始化完毕的代码
            if(ParseItemManager.isInitData() && parseIng == false){
               return true;
            }else{
                try {
                    sleep(1000);
                }
                catch (InterruptedException e) {
//                    e.printStackTrace();
                    LogManager.e(Constant.TAG, "getRunPower: ", e);

                    return false;
                }
                checkCnt++;
                // 等待30秒后sdk仍然未初始化完或其他批量预识别仍未结束则不进行本次批量预识别
                if(checkCnt > 30){
                    return false;
                }
            }
        // 未初始化sdk或其他批量预识别正在进
        /*SDK-673 hewengao 20161114 start*/
        }while(InitUtil.isLoadedBigJar == false || parseIng);
         /*SDK-673 hewengao 20161114 start*/
        return true;
    }
   
        private void execute() throws InterruptedException{
            //history sms parse from new to old
            if(stopParse || threadId != Thread.currentThread().getId()){
                return;
            } 
            long maxTime =0;
            if(allTable){
                maxTime=SysParamEntityManager.getLongParam(Constant.BEFORE_HAND_PARSE_SMS_TIME, 0, Constant.getContext());
            }else{
                JSONObject jsObj=PhoneSmsParseManager.findObjectByPhone(phoneNum);
//                LogManager.e("duoqu_test", "JSONObject jsObj: "+jsObj+" phoneNum: "+phoneNum);
                if(jsObj != null){
                   Object obj =JsonUtil.getValFromJsonObject(jsObj, "maxReceiveTime");
                   if(obj != null){
                       maxTime = Long.valueOf(obj.toString());
//                        LogManager.e("duoqu_test", "JSONObject maxTime: "+maxTime+" phoneNum: "+phoneNum);
                   }
                }
            }
            if(maxTime ==0){
                maxTime=System.currentTimeMillis()+Integer.MAX_VALUE;
//                 LogManager.e("duoqu_test", "maxTime =0 phoneNum: "+phoneNum);
            }
            List<JSONObject> listObj=DuoquUtils.getSdkDoAction().getReceiveMsgByReceiveTime(phoneNum, 
                    0, 
                    maxTime, 
                    maxLimit);
            if(listObj == null || listObj.isEmpty()){
//                 LogManager.e("duoqu_test", "beforeHandParseReceiveSms listObj is null: phoneNum: "+phoneNum);
                return;
            }
            int size = listObj.size();
//            LogManager.e("duoqu_test", "beforeHandParseReceiveSms listObj size: "+size+" phoneNum: "+phoneNum);
            JSONObject tempObj =null;
            long smsReceiveTime =0;
            int i = 0;
            /*SDK-490 hewengao 20160616 start */
            mExtend = getExtendMap();
            HashMap<String, String> extend = new HashMap<String, String>();
            if(mExtend != null){
            	extend.putAll(mExtend);
            }
            /*SDK-490 hewengao 20160616 end */
            for(; i < size; i++){
                tempObj= listObj.get(i);
                smsReceiveTime=Long.valueOf((String)JsonUtil.getValFromJsonObject(tempObj,"smsReceiveTime"));
                if(smsReceiveTime < maxTime){
                    maxTime =smsReceiveTime; //hisory sms parse from new to old
                }
                extend.put(Constant.KEY_IS_SAFE_VERIFY_CODE,  (String)JsonUtil.getValFromJsonObject(tempObj,Constant.KEY_IS_SAFE_VERIFY_CODE));
                ParseSmsToBubbleUtil.parseSmsToBubbleResultMap(
                      (String)JsonUtil.getValFromJsonObject(tempObj,"msgId"),
                      (String)JsonUtil.getValFromJsonObject(tempObj,"phone"),
                      (String)JsonUtil.getValFromJsonObject(tempObj,"msg"),
                      (String)JsonUtil.getValFromJsonObject(tempObj,"centerNum"),
                      smsReceiveTime,
                      parseType,
                      allTable,
                      mResultAddMemory,extend
                        );

                /* SDK-556 huangzhiqiang 20160722 start */
                // 记录当次批量识别的短信数量，用于日志输出
                parseCount++;
                /* SDK-556 huangzhiqiang 20160722 end */
                /*SDK-655 hewengao 20161028 start*/
//                if((i+1) % 10 ==0){
                    if(allTable){
                        SysParamEntityManager.setParam(Constant.BEFORE_HAND_PARSE_SMS_TIME, String.valueOf(maxTime));
                    }
                    sleep(1);
//                }
                 /*SDK-655 hewengao 20161028 end*/
                if(stopParse || threadId != Thread.currentThread().getId()){
                    break;
                }
//                LogManager.i("duoqu_xiaoyuan", "threadid: "+Thread.currentThread().getId()+" threadName: "+Thread.currentThread().getName()+" stopParse: "+stopParse+" parseIng: "+parseIng+" i: "+i);
            }
            if(allTable && (i != size || size % 10 != 0)){
                //save parse sms receive time from new to old,
                //maxTime is relative history sms need parse
                SysParamEntityManager.setParam(Constant.BEFORE_HAND_PARSE_SMS_TIME, String.valueOf(maxTime));
            }

            /* SDK-556 huangzhiqiang 20160722 start */
//            parseAllCnt += size;
//            if(stopParse == false && allTable && parseAllCnt < 500 && size >= maxLimit){
//                sleep(5);
//                execute();
//            }
            /* SDK-556 huangzhiqiang 20160722 end */
        }
        @Override
        public void run() {
            try{
                /* SDK-556 huangzhiqiang 20160722 start */
                /* SDK-699 huagnzhiqiang 20161208 begin */
                mLogExtend.clear();
                mLogExtend.put("num", phoneNum);
                mLogExtend.put("maxLimit", maxLimit);
                DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "executeBeforeParse start ", mLogExtend);
                /* SDK-699 huagnzhiqiang 20161208 end */
                /* SDK-556 huangzhiqiang 20160722 end */

            	  /*SDK-426 hewengao 20160506 start */
            	android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            	Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            	  /*SDK-426 hewengao 20160506 end */
                synchronized (lock) {
                    if(parseIng){
                        stopParse =true;
                    }
                }
                if(getRunPower() == false){
//                    LogManager.e("duoqu_xiaoyuan", "$$$$$$$$$$$$$  duoqu_xiaoyuan getRunPower.false: threadId "+threadId);
                    return;
                }
                synchronized (lock) {
                     if(stopParse){
//                         LogManager.i("duoqu_xiaoyuan", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   duoqu_xiaoyuan stopParse.true start or stop prev");
                         return;
                     }
                     parseIng =true;
                     stopParse =false;
                     threadId = Thread.currentThread().getId();
                }
                execute();
            }catch(Throwable e){
//                e.printStackTrace();
                LogManager.e(Constant.TAG, "run: " , e);

            }finally{
                synchronized (lock) {
                    parseIng = false;
                    stopParse = false;
                    threadId =0;
                }
                /* SDK-556 huangzhiqiang 20160722 start */
                /* SDK-699 huagnzhiqiang 20161208 begin */
                mLogExtend.put("parseCount", parseCount);
                DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "executeBeforeParse end ", mLogExtend);
                /* SDK-699 huagnzhiqiang 20161208 end */
                /* SDK-556 huangzhiqiang 20160722 end */
//                LogManager.i("duoqu_xiaoyuan", "duoqu_xiaoyuan threadid: "+Thread.currentThread().getId()+" stop.");
            }
        }

        /*SDK-490 hewengao 20160616 start */
        /* SDK-657 zhaojiangwei 20161101 start */
        private synchronized Map getExtendMap(){
        /* SDK-657 zhaojiangwei 20161101 end */
        	if(mExtend == null){
        		try{
	        		String parseExtendCfg =DuoquUtils.getSdkDoAction().getExtendConfig(AbsSdkDoAction.EXTEND_CONFIG_PARSE_MSG, null);
	        		if(!StringUtils.isNull(parseExtendCfg)){
	        			mExtend = JsonUtil.parseJSON2Map(parseExtendCfg);
	        		}
        		}catch(Throwable e){
        			LogManager.e("xiaoyuan", "getExtendMap", e);
        		}
        	}  
        	if(mExtend == null){
        		mLoadExtendCount++;
        		if(mLoadExtendCount > 5){
        		    mExtend = new HashMap<String, String>();
        		}
        	}
        	return mExtend;
        }
        /*SDK-490 hewengao 20160616 end */
}
